package edu.kit.aifb.ruleintegrator;

import java.io.File;
import java.io.IOException;

import joptsimple.OptionParser;
import joptsimple.OptionSet;

import org.apache.log4j.Logger;

import edu.kit.aifb.ats.ATSBaseRepository;
import edu.kit.aifb.ats.Configuration;
import edu.kit.aifb.ats.triples.TripleRepository;
import edu.kit.aifb.ats.triples.importer.Importer;
import edu.kit.aifb.ats.triples.importer.NxImporter;
import edu.kit.aifb.ruleintegrator.bayes.StructuralEM;
import edu.kit.aifb.ruleintegrator.bayes.network.NetworkManager;
import edu.kit.aifb.ruleintegrator.repository.RepositoryStatistics;

public class Main {
	
	private static final Logger log = Logger.getLogger(Main.class);

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		OptionParser op = new OptionParser();
		op.accepts("d", "output directory")
			.withRequiredArg().ofType(String.class).describedAs("directory");
		op.accepts("nt", "nt input")
		.withRequiredArg().ofType(String.class).describedAs("NT file");
		op.accepts("w", "working folder")
		.withRequiredArg().ofType(String.class).describedAs("Working Folder");

//		op.accepts("db", "db file")
//		.withRequiredArg().ofType(String.class);
		OptionSet os = op.parse(args);

		if (!os.has("d") || !os.has("w")) {
			op.printHelpOn(System.out);
			return;
		}
		
		String directory = (String)os.valueOf("d");
		String workingdirectory = (String)os.valueOf("w");
		ATSBaseRepository baseRepo = new ATSBaseRepository(new File(directory));
		TripleRepository tr=null; 
		
		

		
		if(os.has("nt")){
			tr= baseRepo.createSubRepository(TripleRepository.class, 
					new Configuration().set(TripleRepository.PARAM_TYPE, TripleRepository.TYPE_TRIPLES));
			String ntfile = (String)os.valueOf("nt");
			Importer importer = new NxImporter();
			importer.addImport(ntfile);
			importer.setNodeSink(tr);
			importer.doImport();
			
			tr.optimize();
			tr.close();

		}
		tr=baseRepo.getSubRepository(TripleRepository.class,false, 
					new Configuration().set(TripleRepository.PARAM_TYPE, TripleRepository.TYPE_TRIPLES));
		
		
//		StructuralEM em=new StructuralEM(null, tr);
//		em.initModel();
//		RepositoryStatistics stats=new RepositoryStatistics(tr);
		RepositoryStatistics stats =RepositoryStatistics.load(workingdirectory);
		
		
		NetworkManager nm=new NetworkManager(tr,stats);
		StructuralEM sem=new StructuralEM(nm);
		sem.execute();
		
		tr.close();
		
		
	
		
		
		
		

	}

}
